const Base = require('./base.js');
const decimal = require('decimal.js');
const moment = require('moment');

module.exports = class extends Base {
  async listAction() {
    const query = this.get();
    const model = this.model('configs');
    const res = await model.getList(query);
    return this.success(res);
  }

  async pageAction() {
    const query = this.get();
    const model = this.model('configs');
    const res = await model.getPage(query);
    return this.success(res);
  }

  async infoAction() {
    const id = this.get('id');
    const model = this.model('configs');
    const res = await model.getInfo(id);
    return this.success(res);
  }

  async createAction() {
    const values = this.post();
    const model = this.model('configs');
    const res = await model.create({
      ...values,
      init_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    });
    return this.success(res);
  }

  async updateAction() {
    const values = this.post();
    const model = this.model('configs');
    const res = await model.update(values);
    return this.success(res);
  }

  async removeAction() {
    const id = this.post('id');
    const model = this.model('configs');
    const res = await model.remove(id);
    return this.success(res);
  }

  async lastAction() {
    const model = this.model('configs');
    const recordModel = this.model('configRecords');
    let res = await model.getLast();
    if (Array.isArray(res)) {
      res = await Promise.all(res.map(async(item) => {
        const ls = await recordModel.getList(item.id);
        item.records = ls;
        let de = decimal(item.init_money);
        item.records.forEach(it => {
          const n = decimal(it.record_money).div(item.init_money_unit).toNumber();
          it.record_money = n;
          de = de.sub(it.record_money);
        });
        item.surplus_money = de.toNumber();
        return item;
      }));
    }

    return this.success(res);
  }
};
